{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

{-# LANGUAGE OverloadedStrings #-}

module FunBot.Sources.WebListener.Gogs
    ( dispatchGogs
    )
where

import Data.Maybe (fromMaybe)
import FunBot.ExtEvents
import FunBot.Sources.WebListener.Util
import Network.HTTP (Request (..))
import Network.URI

import qualified Data.Text as T
import qualified Web.Hook.Gogs as G

makeCommit :: G.Commit -> Commit
makeCommit commit = Commit
    { commitAuthor   = G.userName $ G.commitAuthor commit
    , commitTitle    = takeLine $ G.commitMessage commit
    , commitUrl      = G.commitUrl commit
    , commitAdded    = []
    , commitModified = []
    , commitRemoved  = []
    }

makeRepo :: G.Repository -> Repository
makeRepo repo = Repository
    { repoName  = G.repoName repo
    , repoSpace = G.userUsername $ G.repoOwner repo
    , repoHost  = fromMaybe "UNKNOWN" $ do
        uri <- parseURI $ T.unpack $ G.repoUrl repo
        auth <- uriAuthority uri
        return $ T.pack $ uriRegName auth
    }

fromGogs :: G.Push -> ExtEvent
fromGogs push = GitPushEvent ProjectObject
    { poRepo = makeRepo $ G.pushRepository push
    , poObj  = Push
        { pushBranch  = refToBranch $ G.pushRef push
        , pushCommits = reverse $ map makeCommit $ G.pushCommits push
        }
    }

dispatchGogs push _pushMany request =
    case G.parse $ rqBody request of
        Left e -> do
            putStrLn $ "Web hook source: Gogs: " ++ show e ++ ":"
            print $ rqBody request
        Right pushInfo -> push $ fromGogs pushInfo
